﻿using System.Security.Cryptography;
using System.Text;

namespace Yz.Core.Extensions
{
    public static class Md5EncodeExtension
    {
        /// <summary>
        /// 获得32位md5加密后的字串
        /// </summary>
        /// <param name="argInput"></param>
        /// <returns></returns>
        public static string ToMd5Hash(this string value)
        {
            return value.ToMd5Hash(Encoding.Default);
        }
        /// <summary>
        /// 获得32位md5加密后的字串
        /// </summary>
        /// <param name="argInput"></param>
        /// <returns></returns>
        public static string ToMd5Hash(this string value, Encoding encode)
        {
            var md5Hasher = MD5.Create();
            var data = md5Hasher.ComputeHash(encode.GetBytes(value));
            var sBuilder = new StringBuilder();
            for (var i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
        /// <summary>
        /// 获得16位md5加密后的字串
        /// </summary>
        /// <param name="argInput"></param>
        /// <returns></returns>
        public static string ToMd5Hash16(this string value)
        {
            return value.ToMd5Hash16(Encoding.Default);
        }
        /// <summary>
        /// 获得16位md5加密后的字串
        /// </summary>
        /// <param name="argInput"></param>
        /// <returns></returns>
        public static string ToMd5Hash16(this string value, Encoding encode)
        {
            var md5Hasher = MD5.Create();
            var data = md5Hasher.ComputeHash(encode.GetBytes(value));
            var sBuilder = new StringBuilder();
            for (var i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            var s = sBuilder.ToString().Substring(8, 16);
            return s;
        }
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="input">需要加密的字符串</param>
        /// <param name="encode">字符的编码</param>
        /// <returns></returns>
        public static string ToMD5Encrypt(this string value)
        {
            return value.ToMD5Encrypt(Encoding.UTF8);
        }
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="input">需要加密的字符串</param>
        /// <param name="encode">字符的编码</param>
        /// <returns></returns>
        public static string ToMD5Encrypt(this string value, Encoding encode)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(encode.GetBytes(value));
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }
    }
}
